package features.advance.leetcode.math.easy;

/**
 *  67. 二进制求和
 *
 *  难度：简单
 *
 * 给你两个二进制字符串，返回它们的和（用二进制表示）。
 *
 * 输入为 非空 字符串且只包含数字 1 和 0。
 *
 *
 *
 * 示例 1:
 *
 * 输入: a = "11", b = "1"
 * 输出: "100"
 * 示例 2:
 *
 * 输入: a = "1010", b = "1011"
 * 输出: "10101"
 *
 *
 * 提示：
 *
 * 每个字符串仅由字符 '0' 或 '1' 组成。
 * 1 <= a.length, b.length <= 10^4
 * 字符串如果不是 "0" ，就都不含前导零。
 *
 * @author LIN
 * @date 2021-06-17
 */
public class Offer67 {
    public static void main(String[] args) {
        Solution solution = new Solution() {
            @Override
            public String addBinary(String a, String b) {
                if(a == null || b == null){
                    return null;
                }
                int max = Math.max(a.length(), b.length());
                char[] res = new char[max+1];
                int l = max;
                int carry = 0,sum=0;
                int ia = a.length() - 1,ib = b.length() - 1;
                for (int i = 0 ; i <= max ; i++) {

                    int a1 = ia>=0 ? a.charAt(ia--) - 48 : 0;
                    int b1 = ib>=0 ? b.charAt(ib--) - 48 : 0;

                    sum = a1 ^ b1 ^ carry;
                    res[l--] = (char)(sum+48);
                    /*
                      carry = ( carry + a1 + b1 )/2;
                     */
//                    carry = (a1 & b1) | (carry & a1) | (carry & b1);
                    carry = ( carry + a1 + b1 )/2;
                    System.out.println(sum);
                }
                return new String(res,res[0] == 48?1:0,res.length+(res[0] == 48?-1:0));
            }
        };
        String a = "10"; // 10
        String b = "1"; // 11
        String s = solution.addBinary(a, b);
        System.out.println(s);// 10110

    }
    static class Solution {
        public String addBinary(String a, String b) {
            if(a == null || b == null){
                return null;
            }
            int max = Math.max(a.length(), b.length());
            char[] res = new char[max+1];
            int l = max;
            int carry = 0,sum=0;
            int ia = a.length() - 1,ib = b.length() - 1;
            for (int i = 0 ; i <= max ; i++) {

                int a1 = ia>=0 ? a.charAt(ia--) - 48 : 0;
                int b1 = ib>=0 ? b.charAt(ib--) - 48 : 0;

                sum = a1 ^ b1 ^ carry;
                res[l--] = (char)(sum+48);
                carry = (a1 & b1) | (carry & a1) | (carry & b1);

                System.out.println(sum);
            }
            return new String(res,res[0] == 48?1:0,res.length+(res[0] == 48?-1:0));
        }
    }

}
